package org.sample.net.tcp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class ReadWriteManager {

    private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private String name;

    private Socket socket;

    private BufferedWriter writer;

    private BufferedReader reader;

    private Scanner scanner;

    public ReadWriteManager(String name, Socket socket) throws IOException {
        this.name = name;
        this.socket = socket;
        this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "GBK"));
        this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
        this.scanner = new Scanner(System.in);
    }

    public void read() throws Exception {
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    }

    public void write() throws Exception {
        while (scanner.hasNext()) {
            String message = scanner.nextLine();

            StringBuilder sb = new StringBuilder(df.format(new Date()));
            sb.append(" ").append(name).append("\n");
            sb.append(message);
            writer.write(sb.toString());
            writer.newLine();
            writer.flush();
        }
    }

    public void close() {
        scanner.close();
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}